package ks.server.controllers.commands.general.plugin;

import java.util.Collection;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.plugin.Plugin;
import ks.managers.plugin.PluginManager;
import ks.server.ServerContext;

import org.w3c.dom.Document;

/**
 * Process request to get plugin list
 * @author harry moreno
 *
 */
public class PluginListController implements IProcessMessage {
	
	/** Primary agent to whom we can communicate our messages. */
	Communicator com;
	
	public PluginListController (Communicator com) {
		this.com = com;
	}
	/**
	 * To process the PLUGIN-LIST command we create a request with all known plugins.
	 */
	public boolean process(Message m) {

		PluginManager pm = ServerContext.getPluginManager();
		
		Collection<Plugin> pluginSet = pm.getList();
	 
        // produce request containing all PLUGINS and their respective URLs
        StringBuilder sb = new StringBuilder("<request version='1.0' id='1'><plugins>");
        
        for (Plugin plugin : pluginSet) {
        	sb.append("<plugin-installed name=\"" + plugin.name + "\" losses=\"" + plugin.getLosses() +
        			"\" wins=\"" + plugin.getWins() + "\" date=\"" + plugin.getDate() + "\" suspended=\"" +
        			plugin.getSuspended() + "\"/>");
        }
        
        sb.append("</plugins></request>");
        Document d = Message.construct(sb.toString());
        
        // send to originating client
        Message r = new Message (d);
        r.setRecipient(m.getOriginator());
        
        return com.distribute(r);
	}
}
